<script lang="ts" setup>
import { FormInstance, FormRules } from 'element-plus';
import { nextTick } from 'vue';
import { createUser, updateUser } from '@/api';
import { KeyValue, User } from '@/model';
import { errorNotice } from '@/libs/utils';

const props = defineProps<{
  // 是否打开弹出层
  visible: boolean;
  // 什么动作触发的弹窗？create：新增；update：编辑
  type: string;
  // 当前被点击的行，用作编辑，或新增
  currentRow: User | undefined;
}>();

const emits = defineEmits(['closeDialog', 'submitted']);

const dialogHeight = ref<string>('');
const form = reactive<User>({});
const formRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
});

/**
 * 关闭弹窗，更新默认值
 */
const onClose = () => {
  emits('closeDialog', false, undefined);
  if (!formRef || !formRef.value) {
    return;
  }
  formRef.value.resetFields();
};

/**
 * 新增或编辑提交
 */
const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      if (props.type === 'update') {
        updateUser(form).then(() => {
          emits('submitted');
        });
      } else {
        createUser(form).then(() => {
          emits('submitted');
        });
      }
    } else {
      errorNotice(fields);
    }
  });
};

/**
 * 计算滚动条高度
 */
const calcScrollbarHeight = () => {
  dialogHeight.value = `${window.innerHeight * 0.5}px`;
};


/**
 * 当弹出层被打开时触发
 */
const onOpen = () => {
  calcScrollbarHeight();
  // 编辑
  if (props.type === 'update') {
    form.id = props.currentRow!.id;
    form.username = props.currentRow!.username;
    form.name = props.currentRow!.name;
    form.telPhone = props.currentRow!.telPhone;
    form.email = props.currentRow!.email;
    form.roleNames = props.currentRow!.roleNames;
    form.roleIds = props.currentRow!.roleIds;
    form.deptId = props.currentRow!.deptId;
    form.dataRights = props.currentRow!.dataRights;
    form.remark = props.currentRow!.remark;
  } else {
    form.id = '';
  }
};
</script>

<template>
  <el-dialog
    :model-value="visible"
    :show-close="false"
    @closed="onClose"
    width="60%"
    @open="onOpen"
    :close-on-click-modal="false"
  >
    <template #header>
      <div class="form-header">
        <span class="title">{{ type === 'update' ? '编辑' : '新增' }}</span>
        <div>
          <el-tooltip content="确认" placement="top" effect="light" :show-after="500">
            <el-button class="btn-confirm" circle @click="onSubmit()">
              <el-icon>
                <i-ep-check />
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="取消" placement="top" effect="light" :show-after="500">
            <el-button class="btn-cancel" circle @click.stop="onClose()">
              <el-icon>
                <i-ep-close />
              </el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </template>
    <el-scrollbar :height="dialogHeight" ref="scrollbarRef">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="form"
        size="large"
        :show-message="false"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" class="form-input" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="电话号码" prop="telPhone">
              <el-input v-model="form.telPhone" class="form-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="form.email" class="form-input" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
